/**
 *Copyright (c) 2024 watereyes
 * workflow is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.workflow.api.listener;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.activiti.bpmn.model.ExtensionAttribute;
import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.EngineServices;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.delegate.event.impl.ActivitiActivityEventImpl;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.impl.identity.Authentication;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.koron.workflow.api.service.ActivitiService;
import com.koron.workflow.api.util.ApiUtils;
import com.koron.workflow.common.util.SpringContextHolder;

/**
 * 添加多实例节点变量
 * @author 周利斌
 *
 */
public class ActivityStartedListener extends ProcessListenerAdapter{
	
	private static Logger log = LoggerFactory.getLogger(ActivityStartedListener.class);
	
	private ActivitiService activitiService = SpringContextHolder.getBean(ActivitiService.class);
	
	@Override
	public void activityStarted(ActivitiEvent event) {
		EngineServices engineServices = event.getEngineServices();
		RuntimeService runtimeService = engineServices.getRuntimeService();
		if(event instanceof ActivitiActivityEventImpl) {
			log.info("ActivityStartedListener 已执行.....");
			ActivitiActivityEventImpl activitiEntity = ((ActivitiActivityEventImpl) event);
			UserTask userTask = activitiService.getUserTask(activitiEntity.getProcessDefinitionId(), activitiEntity.getActivityId());
			if(userTask != null) {
				Map<String, List<ExtensionAttribute>> operationmap = userTask.getExtensionElements().get("operation").get(0).getAttributes();
				String type = operationmap.get("type").get(0).getValue();
				if(type != null && StringUtils.equals(type, "approveNode")) {
					@SuppressWarnings("unchecked")
					List<String> users = runtimeService.getVariable(event.getExecutionId(), activitiEntity.getActivityId().replaceAll("-", "") + "_User", List.class);
					Map<String, Object> variables = runtimeService.getVariables(event.getExecutionId());
					HistoricProcessInstance hpis = activitiService.getHistoricProcessInstance(event.getProcessInstanceId());
					String filterRule = operationmap.get("filter_rule").get(0).getValue();
					String autoPickRule = operationmap.get("auto_pick_rule").get(0).getValue();
					String startUserId = hpis == null ? Authentication.getAuthenticatedUserId() : hpis.getStartUserId();
					if(users == null) {
						users = new ArrayList<String>();
					}
					users = ApiUtils.convertUsers(users, startUserId, filterRule, autoPickRule, variables);
					runtimeService.setVariable(event.getExecutionId(), "Loop" + activitiEntity.getActivityId().replaceAll("-", "") + "_User_Size", users.size());
					runtimeService.setVariable(event.getExecutionId(), "Loop" + activitiEntity.getActivityId().replaceAll("-", "") + "_User_List", users);
				}
			}
		}
	}
}
